package com.spicesoft.o3d.client;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.SimplePanel;

public class O3DClient extends Composite {

	private final String clientDivId;
	private final AsyncCallback<Void> callback;
	private JavaScriptObject jsClientElement;

	public O3DClient(AsyncCallback<Void> callback) {
		this.callback = callback;
		clientDivId = System.currentTimeMillis() + "_"
				+ (int) (Math.random() * 100000);

		SimplePanel sp = new SimplePanel();
		DOM.setElementAttribute(sp.getElement(), "id", clientDivId);

		initWidget(sp);
	}

	@Override
	protected void onAttach() {
		super.onAttach();
		init(this, clientDivId);
	}

	private native void init(O3DClient x, String id) /*-{
		$wnd.o3djs.util.makeClients(
			function (clientElements) {
				x.@com.spicesoft.o3d.client.O3DClient::initCallback(Lcom/google/gwt/core/client/JavaScriptObject;)(clientElements[0]);
			},
			null,
			null,
			id
		);
	}-*/;

	/**
	 * Called from JSNI
	 * 
	 * @param clientElement
	 */
	@SuppressWarnings("unused")
	private void initCallback(JavaScriptObject clientElement) {
		this.jsClientElement = clientElement;
		callback.onSuccess(null);
	}

	JavaScriptObject getJSClient() {
		return this.jsClientElement;
	}

}
